import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, convertFromHTML, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const confirm = Modal.confirm;
const { TextArea } = Input;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { seoUpdate, seoDelete, seoAdd } from '../../services/api';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import counties from '../../data/counties.json';

import styles from './seo.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const PAGE_MAP = {
  INDEX: '首页',
  NEWS: '新闻动态',
  POLICY_CONSULTATION: '政策资讯',
  INTELLECTUAL_PROPERTY: '知产干货',
  TRADEMARK_AGENCY_SERVICE: '商标代理服务',
  COPYRIGHT_AGENT_SERVICE: '版权代理服务',
  ASSESSMENT_AND_ANALYSIS_SERVICE: '评估分析服务',
  LEGAL_SERVICE: '法律服务',
  PATENT_AGENCY_SERVICE: '专利代理服务',
  QUALIFICATION_SERVICE: '资质认证服务',
};

let PAGE_ARR = [];
Object.keys(PAGE_MAP).map(key => {
  PAGE_ARR.push({
    id: key,
    name: PAGE_MAP[key],
  });
});

const pageSize = 10;

@connect(({ seo, loading }) => {
  return {
    seo,
    loading: loading.models.seo,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    id: null,
    site: 0,
    type: null,
    title: null,
    keywords: null,
    desc: null,
  };

  componentDidMount() {
    this.init();
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'seo/queryList',
      payload: {
        pageNum: 1,
        pageSize: pageSize,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'seo/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.init();
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        type: fieldsValue.type,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'seo/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      title: '',
      editorState: EditorState.createEmpty(),
    });
  };

  async handleSave(e) {
    const { site, type, title, keywords, description } = this.state;

    if (!type) {
      return message.error('请选择页面');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const { id, site, type, title, keywords, description } = this.state;
    let params = { site, type, title, keywords, description };

    if (id) {
      params.id = id;
      const response = await seoUpdate(params);

      if (response.code === 200) {
        this.setState({
          modalVisible: false,
        });

        this.init();
      } else {
        message.error(response.message);
      }
    } else {
      const response = await seoAdd(params);

      if (response.code === 200) {
        this.setState({
          modalVisible: false,
        });

        this.init();
      } else {
        message.error(response.message);
      }
    }
  }

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={16} sm={24} />

          <Col md={8} sm={24} />
        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" onClick={this.handleShowModal.bind(this)}>
                新建SEO
              </Button>
            </span>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
        </Row>
      </Form>
    );
  }

  handleEdit(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  async handleDelete(item) {
    const { dispatch } = this.props;

    confirm({
      title: '确认删除',
      content: '是否删除？',
      onOk: (async () => {
        let { errno, errmsg, data } = await seoDelete({
          id: item.id,
        });
        if (!errno) {
          message.success('删除成功');
          this.init();
        }
      }).bind(this),
      onCancel() {},
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleSelectOnchange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    let { seo: { data }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '站点类型',
        dataIndex: 'site',
        render: (val, item) => <span>{val === 0 ? 'WEB端' : '移动端'}</span>,
      },
      {
        title: '页面',
        dataIndex: 'type',
        render: (val, item) => <span>{PAGE_MAP[val]}</span>,
      },
      {
        title: 'Title',
        dataIndex: 'title',
      },
      {
        title: 'Keywords',
        dataIndex: 'keywords',
      },
      {
        title: 'Description',
        dataIndex: 'description',
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>&nbsp;
            <a onClick={this.handleDelete.bind(this, item)}>删除</a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="SEO 列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>

            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          style={{ width: '800px' }}
          title="新建SEO"
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <DescriptionList size="large" title="" col="1">
            <Description term="站点类型">
              <RadioGroup onChange={this.onRadioChange.bind(this, 'site')} value={this.state.site}>
                <Radio value={0}>WEB端</Radio>
                <Radio value={1}>移动端</Radio>
              </RadioGroup>
            </Description>
            <Description term="页面">
              <Select
                value={this.state.type}
                onChange={this.handleSelectOnchange.bind(this, 'type')}
                placeholder="请选择"
                style={{ width: '100%' }}
              >
                {PAGE_ARR.map(item => {
                  return (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Description>
            <Description term="Title">
              <Input value={this.state.title} onChange={this.handleOnchange.bind(this, 'title')} />{' '}
            </Description>
            <Description term="Keywords">
              <Input
                value={this.state.keywords}
                onChange={this.handleOnchange.bind(this, 'keywords')}
              />{' '}
            </Description>
            <Description term="Description" termStyle={styles.top}>
              <TextArea
                rows={4}
                value={this.state.description}
                onChange={this.handleOnchange.bind(this, 'description')}
              />
            </Description>
          </DescriptionList>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
